﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Yunchang.ILUI
{
    /// <summary>
    /// UI元素的挂件
    /// </summary>
    public class UIBase : MonoBehaviour
    {
        /// <summary>
        /// View 存储逻辑使用的UI挂件
        /// </summary>
        private Dictionary<string, object> mProperty = new Dictionary<string, object>();

        /// <summary>
        /// 动态参数设置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object this[string key]
        {
            get
            {
                object o = null;
                if (mProperty.TryGetValue(key, out o))
                {
                    return o;
                }
                return null;
            }
            set
            {
                mProperty[key] = value;
            }
        }

        public T GetObject<T>(string key) where T : new()
        {
            if (this[key] == null)
                this[key] = new T();
            return (T)this[key];
        }
        public void RemoveObject(string key)
        {
            mProperty.Remove(key);
        }

        #region View UI Event
        /// <summary>
        /// 给UI元素的事件 回调注册 执行
        /// </summary>
        /// <typeparam name="T0"></typeparam>
        /// <param name="key"></param>
        /// <param name="call"></param>
        /// <returns></returns>
        public LambdaObject<UIEventListener, T0> AddListener<T0>(string key, ref UIEventListener.VoidDelegate call)
        {
            if (this[key] == null)
            {
                var lobj = LambdaObjectPool<LambdaObject<UIEventListener, T0>>.Ins.Get();
                call = lobj.Execute;
                this[key] = lobj;
            }
            return this[key] as LambdaObject<UIEventListener, T0>;
        }
        public void RemoveLister<T0, T1>(string key, ref UIEventListener.VoidDelegate call)
        {
            var lobj = this[key] as LambdaObject<UIEventListener, T0>;
            if (lobj != null)
            {
                call = null;
                LambdaObjectPool.Relase(lobj);
                this[key] = null;
            }
        }
        #endregion

        protected virtual void OnDestroy()
        {
            var erator = mProperty.GetEnumerator();
            while (erator.MoveNext())
            {
                var obj = erator.Current.Value as ILambdaObject;
                if (obj != null)
                    LambdaObjectPool.Relase(obj);
            }
            mProperty.Clear();
        }
    }
}
